﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media;
using VBFOOL.MediaPlayer.Core.Interface;
namespace VBFOOL.MediaPlayer.Core
{
    public class OpenMediaStreamSource : MediaStreamSource
    {
        public OpenMediaStreamSource(IInputSource source)
        {
            this.Source = source;
            AudioBufferLength = 300;
        }

        public IInputSource Source { get; private set; }

        protected override void CloseMedia()
        {

        }

        protected override void GetDiagnosticAsync(MediaStreamSourceDiagnosticKind diagnosticKind)
        {
            //throw new NotImplementedException();
        }

        protected override void GetSampleAsync(MediaStreamType mediaStreamType)
        {
            IMediaStream ms;
            if (mediaStreamType == MediaStreamType.Video)
            {
                ms = VideoStream;
            }
            else
            {
                ms = AudioStream;
            }
            if (ms.BufferProgress >= 1)
            {
                try
                {
                    var f = ms.GetFrame();
                    ReportGetSampleCompleted(new MediaStreamSample(ms.CurrentTrack.Description, f.Data, f.Position, f.Length, f.TimeCode, new Dictionary<MediaSampleAttributeKeys, string>()));
                }
                catch (Exception)
                {
                    ErrorOccurred("播放失败");
                }
            }
            else
            {
                ReportGetSampleProgress(ms.BufferProgress);
            }
        }

        protected override void OpenMediaAsync()
        {
            try
            {
                Dictionary<MediaSourceAttributesKeys, string> srcatt = new Dictionary<MediaSourceAttributesKeys, string>();
                srcatt[MediaSourceAttributesKeys.CanSeek] = Source.CanSeek.ToString();
                srcatt[MediaSourceAttributesKeys.Duration] = Source.Duration.ToString("F0");
                Source.BuildStreams();
                VideoStream = Source.VideoStream;
                AudioStream = Source.AudioStream;
                ReportOpenMediaCompleted(srcatt, Source.Tracks.Select(m => m.Description));
            }
            catch (Exception ex)
            {
                ErrorOccurred(string.Format("打开媒体源出错,{0}", ex.Message));
            }

        }

        protected override void SeekAsync(long seekToTime)
        {
            ReportSeekCompleted(Source.Seek(seekToTime));
        }

        IMediaStream VideoStream = null;
        IMediaStream AudioStream = null;

        protected override void SwitchMediaStreamAsync(MediaStreamDescription mediaStreamDescription)
        {
            Source.ChangeAudioTrack(mediaStreamDescription);
            ReportSwitchMediaStreamCompleted(mediaStreamDescription);
        }
    }
}
